import websocket
import datetime
import hashlib
import base64
import hmac
import json
from urllib.parse import urlencode
import time
import ssl
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
import _thread as thread
import os
import wave
import subprocess

from util import sound_play

STATUS_FIRST_FRAME = 0  # 第一帧的标识
STATUS_CONTINUE_FRAME = 1  # 中间帧标识
STATUS_LAST_FRAME = 2  # 最后一帧的标识

APPID = '1e6dbc87'
APIKey = '92547e79b07baaf56717c0f915022fae'
APISecret = 'ZmNiYmExODRmNzllY2IzN2Y1ZDAzYjE5'

# 音色字典
VOICE_MAP = {
    "高冷女声": "x4_lingxiaoyun_talk",
    "温柔女声": "x4_lingxiaoying_en",
    "成熟男声": "x4_lingbosong",
    "男旁白": "x4_guanshan_talk",
    "女孩": "x_lele",
    "男孩": "x4_doudou"
}

class Ws_Param(object):
    def __init__(self, APPID, APIKey, APISecret, Text, Voice):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.Text = Text

        # 公共参数(common)
        self.CommonArgs = {"app_id": self.APPID}
        # 业务参数(business)
        self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": Voice, "tte": "utf8"}
        self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}

    def create_url(self):
        url = 'wss://tts-api.xfyun.cn/v2/tts'
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
            self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        v = {
            "authorization": authorization,
            "date": date,
            "host": "ws-api.xfyun.cn"
        }
        url = url + '?' + urlencode(v)
        return url

def on_message(ws, message):
    try:
        message = json.loads(message)
        code = message["code"]
        sid = message["sid"]
        audio = message["data"]["audio"]
        audio = base64.b64decode(audio)
        status = message["data"]["status"]
        if status == 2:
            ws.close()
        if code != 0:
            errMsg = message["message"]
            print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
        else:
            with open('./demo.pcm', 'ab') as f:
                f.write(audio)

    except Exception as e:
        print("receive msg,but parse exception:", e)


def on_error(ws, error):
    print("### error:", error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        d = {"common": wsParam.CommonArgs,
             "business": wsParam.BusinessArgs,
             "data": wsParam.Data}
        d = json.dumps(d)
        ws.send(d)
        if os.path.exists('./demo.pcm'):
            os.remove('./demo.pcm')

    thread.start_new_thread(run, ())

def pcm2wav(pcm_file, wav_file, channels=1, bits=16, sample_rate=16000):
    pcmf = open(pcm_file, 'rb')
    pcmdata = pcmf.read()
    pcmf.close()

    wavfile = wave.open(wav_file, 'wb')
    wavfile.setnchannels(channels)
    wavfile.setsampwidth(bits // 8)
    wavfile.setframerate(sample_rate)
    wavfile.writeframes(pcmdata)
    wavfile.close()
    # play_wav(wav_file)
    # sound_play()

def play_wav(wavfile):
    try:
        subprocess.run(["start", wavfile], shell=True)
    except Exception as e:
        print(f"An error occurred while trying to play the WAV file: {e}")

def generate_and_play_voice(text, voice):

    if voice not in VOICE_MAP:
        print("Invalid voice type. Available types are:", list(VOICE_MAP.keys()))
        return

    global wsParam
    wsParam = Ws_Param(APPID=APPID, APIKey=APIKey, APISecret=APISecret, Text=text, Voice=VOICE_MAP[voice])
    websocket.enableTrace(False)
    wsUrl = wsParam.create_url()
    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
    pcm2wav("demo.pcm", "demo.wav")

if __name__ == "__main__":
    # 示例：生成并播放音频
    generate_and_play_voice(
        text="沁园春·雪   北国风光，千里冰封，万里雪飘。望长城内外，惟余莽莽；大河上下，顿失滔滔。",
        voice="男旁白"
    )
